import time
from datetime import datetime
from random import random

import requests

from app.models import Enterprise, CustomerServicer, GasStation, WxworkGroupy, WxworkGroupyMember, GasStationDayReport, \
    Saleman, Trainer
from spider.AIYZ.AIYZAdminSpider import AIYZAdminSpider
from util.jsonUtil import getJsonObjectValue

def getSalemansJson():
    list = Saleman.objects.all()
    salemans={}
    for o in list:
        salemans[o.name]=o
    return salemans

def getTrainersJson():
    list = Trainer.objects.all()
    trainers={}
    for o in list:
        trainers[o.name]=o
    return trainers

def getCustomerServicersJson():
    list = CustomerServicer.objects.all()
    CustomerServicers={}
    for o in list:
        CustomerServicers[o.name]=o
    return CustomerServicers


def getEnterprisesInfoListByCreateTime(spider,server_site):
    """
        取得所有创建时间之后的所有企业号的信息
    :type createTime: object
    """
    currentCount = Enterprise.objects.filter(server_site=server_site).count()
    pageSize = 20

    url = "https://%s/api/enterprise/admin/enterprise/page-list?page=%s&size=%s&token=%s" % (
        spider.host, 1, pageSize, spider.token)
    json1 = spider.get(url, headers=spider.header).json()
    print(json1)
    pageTotal = json1["data"]["pageTotal"]

    lastPage= pageTotal-currentCount//pageSize
    print("lastPage = ",lastPage)


    customerServicers  =getCustomerServicersJson()
    salemans = getSalemansJson()

    while (True):
        url = "https://%s/api/enterprise/admin/enterprise/page-list?page=%s&size=%s&token=%s" % (
            spider.host, lastPage, pageSize, spider.token)
        json1 = spider.get(url, headers=spider.header).json()
        print(json1)
        pageTotal = json1["data"]["pageTotal"]
        list1 = json1["data"]["rows"]
        list1.reverse()
        print(list1)
        for o in list1:
            print(o["name"])
            if Enterprise.objects.filter(id=o["id"]).count()>=1:
                print(o["id"],"已经添加了！")
                continue
            print("客服",o["csUserName"])
            csUserName=customerServicers[o["csUserName"]] if (o["csUserName"] in customerServicers) else customerServicers["黄秀贞"]
            saleman = salemans[o["bmUserName"]] if (o["bmUserName"] in salemans) else salemans["陈宗标"]

            print("保存")


            Enterprise.objects.create(id=o["id"],name=o["name"],address=o["address"],status=o["status"],server_site=server_site,saleman=saleman,customerServicer=csUserName).save()


        currentCount = Enterprise.objects.filter(server_site=server_site).count()
        pageTotal = json1["data"]["pageTotal"]
        lastPage = pageTotal - currentCount // pageSize-1
        if lastPage < 1:
            break

def getGasStationInfoListByCreateTime(spider,server_site):
    currentCount = GasStation.objects.filter(server_site=server_site).count()
    pageSize = 20

    url = "https://%s/api/enterprise/admin/gas-station/page-list?page=%s&size=%s&token=%s" % (
        spider.host, 1, pageSize, spider.token)
    json1 = spider.get(url, headers=spider.header).json()
    print(json1)
    pageTotal = json1["data"]["pageTotal"]

    lastPage= pageTotal-currentCount//pageSize
    print("lastPage = ",lastPage)

    defaul_csUserName = CustomerServicer.objects.filter(name="黄秀贞").first()

    defaul_enterprise = Enterprise.objects.filter(id="1080374662174629890").first()
    while (True):
        url = "https://%s/api/enterprise/admin/gas-station/page-list?page=%s&size=%s&token=%s" % (
            spider.host, lastPage, pageSize, spider.token)
        json1 = spider.get(url, headers=spider.header).json()
        print(json1)

        list1 = json1["data"]["rows"]
        list1.reverse()
        print(list1)
        for o in list1:
            print(o["name"])
            if GasStation.objects.filter(id=o["id"]).count()>=1:
                print(o["id"],"已经添加了！")
                continue

            enterprise1 = Enterprise.objects.filter(id=o["enterpriseId"]).first()
            print("enterpriseId = ",o["enterpriseId"])
            if enterprise1 is None:
                enterprise1 = defaul_enterprise
            print("保存")

            csUserName = defaul_csUserName
            if enterprise1.customerServicer is not None:
                csUserName =enterprise1.customerServicer
            saleman = enterprise1.saleman
            status = enterprise1.status
            GasStation.objects.create(id=o["id"],name=o["name"],province=o["province"],area=o["area"]
                                      ,city=o["city"]
                                      ,address=o["address"]
                                      ,lat=o["lat"]
                                      ,lng=o["lng"]
                                      ,gasstationcode=o["gasStationCode"]
                                      ,enterprise=enterprise1
                                      ,phone=o["phone"]
                                      ,saleman =saleman
                                      , status=status
                                      ,create_date= datetime.strptime(o["createTime"],'%Y-%m-%d %H:%M:%S')
                                      ,            server_site=server_site,customerServicer=csUserName).save()


        currentCount = GasStation.objects.filter(server_site=server_site).count()
        pageTotal = json1["data"]["pageTotal"]
        lastPage = pageTotal - currentCount // pageSize-1
        if lastPage < 1:
            break




def update_enterpise_task():
    print('---------    update_enterpise_task     start  ---------------')

    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "5XDF652CFM7XPIWX6WOBJXAOAKGEZWMZ",host="admin.aiyouzhan.cn");
    spide1.login()
    getEnterprisesInfoListByCreateTime(spide1,"稳定服务器")

    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "MRDMFFHLMCCS64IBWHW2OUKB5HDHGGWP",host="admin.beta.aiyouzhan.cn");
    spide1.login()
    getEnterprisesInfoListByCreateTime(spide1,"试点服务器")

    print('---------    update_enterpise_task    end   ---------------')

def update_gasStation_task():
    print('---------    update_gasStation_task     start  ---------------')

    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "MRDMFFHLMCCS64IBWHW2OUKB5HDHGGWP",host="admin.beta.aiyouzhan.cn");
    spide1.login()
    getGasStationInfoListByCreateTime(spide1,"试点服务器")

    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "5XDF652CFM7XPIWX6WOBJXAOAKGEZWMZ",host="admin.aiyouzhan.cn");
    spide1.login()
    getGasStationInfoListByCreateTime(spide1,"稳定服务器")

    print('---------    update_gasStation_task    end   ---------------')

def updateWxwrokGroup(cookie):
    url = "https://work.weixin.qq.com/wework_admin/customer/getGroupChatList?lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random=0.05627253393938636&off_set=10&limit=10&create_ts_begin=1617292800&create_ts_end=1622863316&page=2&accurate_keywords=&_d2st=a9051282"

    payload = {}
    headers = {
        'authority': 'work.weixin.qq.com',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'x-requested-with': 'XMLHttpRequest',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'content-type': 'application/x-www-form-urlencoded',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://work.weixin.qq.com/wework_admin/frame',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie': cookie
    }
    off_set=0
    while True:
        data = {'lang': 'zh_CN', 'f': 'json', 'ajax': 1, 'timeZoneInfo[zone_offset]': '-8',
                'random': random(), 'off_set': off_set, 'limit': 10, 'create_ts_begin': 1617292800,
                'create_ts_end': 2538014249, 'page': 1,
                'accurate_keywords': '', '_d2st': 'a9051282'}
        url = "https://work.weixin.qq.com/wework_admin/customer/getGroupChatList"
        response = requests.request("GET", url, headers=headers, params=data)
        json1 = response.json()
        print(json1)
        list  = json1["data"]["datalist"]
        total =  json1["data"]["total"]
        for o  in list:
            e =  WxworkGroupy.objects.filter(id=o["roomid"]).first()
            if e is None :
                WxworkGroupy.objects.create(id=o["roomid"]).save()
                e = WxworkGroupy.objects.filter(id=o["roomid"]).first()
            e.vid=o["vid"]
            e.roomName=o["roomname"]
            e.adminName=o["adminName"]
            e.room_member_version=o["id"]
            e.new_room_name=o["new_room_name"]
            e.departName=o["departName"]
            e.foreign_mem_cnt=o["foreign_mem_cnt"]
            e.roomImage=o["roomimage"]
            e.member_count=o["member_count"]
            #e.notice=o["notice"]
            #e.notice_sender=o["notice_sender"]
            #e.notice_time=o["notice_time"]
            #e.qrcode_url=o["qrcode_url"]
            #e.active_time=datetime.fromtimestamp(o["active_time"])

            e.createtime=datetime.fromtimestamp(o["createtime"])
            e.updatetime=datetime.fromtimestamp(o["updatetime"])
            e.save()
            off_set +=1
        if off_set>= total:
            break
    print("微信群采集完成")
def updateWxwrokGroupMemberd(cookie):
    print("微信群成员采集开始")
    list =WxworkGroupy.objects.all()
    for o in list:
        updateWxwrokGroupMemberById(cookie,o.id)
    print("微信群成员采集完成")

def updateWxwrokGroupMemberById(cookie,roomid):
    e = WxworkGroupy.objects.filter(id=roomid).first()
    if e is None:
        return
    print("采集%s...." % e.new_room_name)
    headers = {
        'authority': 'work.weixin.qq.com',
        'accept': 'application/json, text/javascript, */*; q=0.01',
        'x-requested-with': 'XMLHttpRequest',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'content-type': 'application/x-www-form-urlencoded',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://work.weixin.qq.com/wework_admin/frame',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cookie': cookie
    }
    off_set=0
    data = {'lang': 'zh_CN', 'f': 'json', 'ajax': 1, 'timeZoneInfo[zone_offset]': '-8',
            'random': random(), 'off_set': off_set, 'limit': 600, 'roomid':roomid, 'page': 1,
            'accurate_keywords': '', '_d2st': 'a9051282'}
    url = "https://work.weixin.qq.com/wework_admin/customer/qun/getRoomMemberList"
    response = requests.request("GET", url, headers=headers, params=data)
    json1 = response.json()
    print(json1)

    e.notice = json1["data"]["notice"]
    e.notice_sender = json1["data"]["notice_sender"]
    #e.notice_time = json1["data"]["notice_time"]
    e.qrcode_url = json1["data"]["qrcode_url"]

    e.save()
    list = json1["data"]["members"]
    print("删除ID", roomid)
    WxworkGroupyMember.objects.filter(wxworkGroupy__id=e.id).delete()

    for o  in list:
        print(o)
        WxworkGroupyMember.objects.create(id="%s_%s" %(roomid,getJsonObjectValue(o,"vid","")),
                                          corpid=getJsonObjectValue(o,"corpid",""),
                                          corp_name=getJsonObjectValue(o,"corp_name",""),
                                          inviter_name=getJsonObjectValue(o,"inviter_name",""),
                                          join_scene=getJsonObjectValue(o,"join_scene",""),
                                          jointime=datetime.fromtimestamp(o["jointime"]),
                                          nickname=getJsonObjectValue(o,"nickname",""),
                                          wxworkGroupy =e ,
                                          ).save()

    print("采集完成")


# 取得昨天的数据汇给
def getAIGasStationDateReport():
    print('Tick! The time is: %s' % datetime.now())
    dateStr ='2021-06-30'
    date = datetime.strptime(dateStr, "%Y-%m-%d")
    spide = AIYZAdminSpider('robot', 'yjd@1234', "5XDF652CFM7XPIWX6WOBJXAOAKGEZWMZ", host="admin.beta.aiyouzhan.cn");
    spide.login()


    list = spide.getGasStationDateReport(date,"",spide.token)
    for o in list:
        id ="%s_%s" %(dateStr,o["stationId"])
        e = GasStationDayReport.objects.filter(id=id).first()
        if e is None:
            gasStation = GasStation.objects.filter(id=o["stationId"]).first()
            print("添加 %s" % o["stationName"])
            e  = GasStationDayReport.objects.create(id=id,date=dateStr,turnover=o["totalAmountToday"],yestoday_turnover=o["totalAmountYestoday"],gasStation=gasStation).save()
        else:
            print("已经添加了！")

    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "5XDF652CFM7XPIWX6WOBJXAOAKGEZWMZ",);
    spide1.login()
    list = spide1.getGasStationDateReport(date,"",spide1.token)
    for o in list:
        print(o)
        id ="%s_%s" %(dateStr,o["stationId"])
        e = GasStationDayReport.objects.filter(id=id).first()
        if e is None:
            gasStation = GasStation.objects.filter(id=o["stationId"]).first()
            e  = GasStationDayReport.objects.create(id=id,date=dateStr,turnover=o["totalAmountToday"],yestoday_turnover=o["totalAmountYestoday"],gasStation=gasStation).save()
        else:
            print("已经添加了！")